using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using UnityEngine;
using XLua;

public class LuaManager : MonoBehaviour
{
    public static LuaEnv luaEnv;
    private static readonly string luaPath = "Script/Lua";

    private void Awake()
    {
        luaEnv = new LuaEnv();
        luaEnv.AddBuildin("rapidjson", XLua.LuaDLL.Lua.LoadRapidJson);
        luaEnv.AddBuildin("lpeg", XLua.LuaDLL.Lua.LoadLpeg);
        luaEnv.AddBuildin("pb", XLua.LuaDLL.Lua.LoadLuaProfobuf);
        luaEnv.AddBuildin("ffi", XLua.LuaDLL.Lua.LoadFFI);

        if (Application.platform == RuntimePlatform.WindowsEditor)
        {
            luaEnv.AddLoader(((ref string filepath) =>
            {
                string fullPath = Path.Combine(Application.dataPath, luaPath, filepath + ".lua");
                if (File.Exists(fullPath))
                {
                    StreamReader streamReader = new StreamReader(fullPath);
                    string content = streamReader.ReadToEnd();
                    streamReader.Close();
                    return System.Text.Encoding.UTF8.GetBytes(content);
                }

                return null;
            }));
        }
    }

    private void Start()
    {
        luaEnv.DoString("require('Game/Main')");
    }

    private void OnDestroy()
    {
        luaEnv.Dispose();
    }
}